//
//  HistoryManager.m
//  Logistics
//
//  Created by 刘峰 on 2017/2/17.
//  Copyright © 2017年 com.Logistics. All rights reserved.
//

#import "HistoryManager.h"
#import <FMDB.h>

@interface HistoryManager ()

@property (nonatomic, strong) FMDatabase *dataBase;

@end

@implementation HistoryManager

+ (instancetype)shareHistory{
    static HistoryManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[HistoryManager alloc] init];
    });
    return manager;
}

-(void)createATable:(NSString *)tableName {
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, 1) firstObject] stringByAppendingPathComponent:@"History.db"];
    
    _dataBase = [FMDatabase databaseWithPath:filePath];
    if ([_dataBase open]) {
        BOOL result = [_dataBase executeUpdate:[NSString stringWithFormat:@"CREATE TABLE %@ (HID INTEGER PRIMARY KEY autoincrement, RECORD TEXT)",tableName]];
        if (result) {
            NSLog(@"创建表格成功 path = %@",filePath);
        }
    }
}

-(void)insertHistory:(NSString *)text AtTable:(NSString *)tableName {
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE RECORD = ?", tableName];
    FMResultSet *res = [_dataBase executeQuery:sql, text];
    
    if ([res next]) {
        NSLog(@"已经存在\n");
    }else {
        
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (RECORD) VALUES (?)",tableName];
        BOOL success = [_dataBase executeUpdate:sql, text];

        NSLog(@"是否添加数据成功 %d\n", success);
    }
}


-(NSMutableArray *)deleteTableOfName:(NSString *)tableName{
    [_dataBase executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@", tableName]];
    return [NSMutableArray array];
}

- (NSMutableArray *)getAllHistory:(NSString *)tableName{

    FMResultSet *res = [_dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY HID DESC",tableName]];
    NSMutableArray *dataArray = [NSMutableArray array];
    while ([res next]) {
        NSString *history = [res stringForColumn:@"RECORD"];
        [dataArray addObject:history];
    }
    [res close];
    return dataArray;
}


@end
